import os

from Logger import *


def read(filepath, mode, need_split=False, encoding=None):
    if not os.path.isfile(filepath):
        return None
    try:
        fd = open(filepath, mode, encoding=encoding)
        filedata = fd.read()
        if need_split:
            filedata = filedata.split('\n')
        fd.close()
    except Exception as e:
        LOG(LEVEL_WARN, "Can not read file: [{}], error=[{}]".format(filepath, str(e)))
        return None
    return filedata

def write(filepath, mode, data, splited=False, encoding=None):
    if not filepath:
        return None
    if len(data) < 1:
        return None
    try:
        fd = open(filepath, mode, encoding=encoding)
        if not splited:
            fd.write(data)
        else:
            for index in range(0, len(data)):
                fd.write(data[index] + "\n")
        fd.close()
    except Exception as e:
        LOG(LEVEL_WARN, "Can not read file: [{}], error=[{}]".format(filepath, str(e)))
        return None
    return data